import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:sports_new/entity/expert/expert_rate_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/server/api/expert_api.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import '../../widgets/base/qkd_text.dart';
import '../../widgets/card.dart';

class ExpertRateChart extends StatefulWidget {
  const ExpertRateChart({super.key, required this.expertId, required this.sportId});

  final String expertId;
  final int sportId;

  @override
  State<ExpertRateChart> createState() => _ExpertRateChartState();
}

class _ExpertRateChartState extends State<ExpertRateChart> {
  List<ExpertRateEntity>? entity;
  List<Color> color = [Colours.main,Colours.grey66,Colours.blue2766D6];
  List<String> type = ["胜","平","负"];
  List<String> text = [];
  List<bool> show = List.generate(3, (index) => true);
  List<String> title = [];
  List<double> rate = [];
  List<String> tag = [];
  int showSpot = 0;

  @override
  void initState() {
    getData();
    super.initState();
  }

  Future getData() async{
    List<ExpertRateEntity>? data = await ExpertApi.getExpertRate(widget.expertId, widget.sportId);
    setState(() {
      entity = data;
      rate = entity?.map((e) => e.hit ?? 0).toList() ?? [];
      title = entity?.map((e) => "近${e.total ?? 0}场").toList() ?? [];
      tag = entity?.map((e) => e.tag ?? "").toList() ?? [];
      showSpot = rate.indexOf(rate.max()?.toDouble() ?? 0);
    });
  }

  @override
  Widget build(BuildContext context) {
    return LoadingWidget<bool>(
      isLoading: entity == null,
      loading: Container(),
      data: entity?.length == 0,
      noData: Container(),
      child: () => Block(
        cardStyle: const CardStyle(
            padding: EdgeInsets.fromLTRB(12, 16, 12, 12),
            margin: EdgeInsets.fromLTRB(8, 8, 8, 0)
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            QkdText("近期命中率",
              fontSize: 16,
              fontWeight: FontWeight.w600
            ),
            Container(height: 30),
            Stack(
              children: [
                Positioned.fill(
                  right: 16,
                  bottom: 23,
                  left: 43,
                  child: Row(
                    children: [
                      Expanded(child: Container(color: Colours.greyF7)),
                      Expanded(child: Container(color: Colours.greyFB)),
                      Expanded(child: Container(color: Colours.greyF7))
                    ],
                  ),
                ),
                SizedBox(
                  height: 140,
                  child: LineChart(
                    LineChartData(
                      minY: 0,
                      maxY: 100,
                      lineBarsData: [line()],
                      titlesData: FlTitlesData(
                        topTitles: const AxisTitles(
                            axisNameSize: 0,
                            axisNameWidget: QkdText("")),
                        rightTitles: const AxisTitles(axisNameWidget: QkdText("")),
                        leftTitles: AxisTitles(
                            sideTitles: SideTitles(
                              reservedSize: 44,
                              showTitles: true,
                              interval: 25,
                              getTitlesWidget: (value, meta) {
                                return value == 0?Container():Container(
                                  margin: const EdgeInsets.only(right: 9),
                                  alignment: Alignment.centerRight,
                                  child: QkdText("${value.toInt()}%",
                                    fontSize: 12,color: Colours.grey66
                                  ),
                                );
                              }
                            )
                        ),
                        bottomTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            interval: 1,
                            getTitlesWidget: (value, meta) {
                              return Padding(
                                padding: const EdgeInsets.only(top: 7),
                                child: QkdText(title[value.toInt()],
                                  fontSize: 12,color: Colours.grey66
                                ),
                              );
                            }
                          )
                        )
                      ),
                      gridData: FlGridData(
                          horizontalInterval: 24.99,
                          drawVerticalLine: false,
                          getDrawingHorizontalLine: (value) =>
                          const FlLine(color: Colours.greyD7,dashArray: [3,3],strokeWidth: 1)
                      ),
                      borderData: FlBorderData(
                          border: const Border(
                              bottom: BorderSide(color: Colours.greyD7,width: 1))
                      ),
                      showingTooltipIndicators: [ShowingTooltipIndicators([LineBarSpot(line(), showSpot, line().spots[showSpot])])],
                      lineTouchData: LineTouchData(
                        handleBuiltInTouches: false,
                        touchCallback: (FlTouchEvent event,LineTouchResponse? response) {
                          if(event is FlTapUpEvent && response?.lineBarSpots?.first.spotIndex != null){
                            setState(() {
                              showSpot = response!.lineBarSpots!.first.spotIndex;
                            });
                          }
                        },
                        touchTooltipData: LineTouchTooltipData(
                            getTooltipColor: (LineBarSpot touchedSpot) => Colours.main,
                            fitInsideHorizontally: true,
                            tooltipPadding: const EdgeInsets.symmetric(horizontal: 4,vertical: 2),
                            tooltipMargin: 12,
                            getTooltipItems: (touchedSpots) => touchedSpots.map((e) {
                              var index = e.x.toInt();
                              return LineTooltipItem(
                                  "近${entity?[index].total}中${entity?[index].win} ${e.y.toInt()}%",
                                  const TextStyle(color: Colours.white,fontSize: 10)
                                );
                            }
                            ).toList()
                        ),
                        getTouchedSpotIndicator: (barData, indicators) =>
                          indicators.map((e) => TouchedSpotIndicatorData(
                            const FlLine(color: Colours.main,strokeWidth: 0.5),
                            FlDotData(
                                getDotPainter: (spot,xPercentage, bar, index) =>
                                    FlDotCirclePainter(
                                        radius: 2,
                                        strokeColor: barData.color?.withOpacity(0.5)
                                            ?? Colours.transparent,
                                        color: barData.color ?? Colours.transparent,
                                        strokeWidth: 2)
                            )
                          )).toList()
                      )
                    )
                  ),
                ),
              ],
            ),
          ],
        ),
      )
    );
  }

  LineChartBarData line(){
    return LineChartBarData(
        barWidth: 1,
        spots: List.generate(rate.length, (i) =>
            FlSpot(i.toDouble(), rate[i])),
        color: Colours.main,
        belowBarData: BarAreaData(
          show: true,
          gradient: LinearGradient(
            colors: [Colours.main.withOpacity(0.5),Colours.transparent],
            begin: Alignment.topCenter,end: Alignment.bottomCenter,
          ),
        ),
        showingIndicators: [showSpot],
        dotData: FlDotData(
            getDotPainter: (spot,xPercentage, bar, potIndex) =>
                FlDotCirclePainter(
                    radius: 2,color: Colours.main,strokeWidth: 1,strokeColor: Colours.white)
        )
    );
  }
}
